package org.testmyapp.persistence;

import java.io.Serializable;

import javax.enterprise.context.SessionScoped;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

@Named
@SessionScoped
public class ConfigObjectPersistenceProvider implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = -2601615431169339149L;
	private static final String persistenceUnit = "customerPersistenceUnit";

	private EntityManagerFactory emf;
	private EntityManager em;

	/**
	 * A whole transaction is used to persist Object.
	 * @param bo (BusinessObjectMarker)
	 * @return boolean whether "bo" was persisted or not
	 */
	public boolean persist(ConfigObjectMarker bo) {
		initEntityManager();
		EntityTransaction transaction = em.getTransaction();
		transaction.begin();
		em.persist(bo);
		transaction.commit();
		return true;
	}
	
	public <T> T find(Class T,Object argument) {
		initEntityManager();
		EntityTransaction transaction = em.getTransaction();
		transaction.begin();
		T result = (T) em.find(T, argument);
		transaction.commit();
		return result;
	}

	private void initEntityManager() {
		if (emf == null) {
			emf = Persistence.createEntityManagerFactory(persistenceUnit);
		}
		if (em == null) {
			em = emf.createEntityManager();
		}
	}

}
